﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Candy.Infrastructure;
using Candy.Model;
using Candy.Resources;
using Candy.Web;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using Candy.Web.Data;

namespace Candy.ViewModel
{
    public class RegistrationViewModel : ViewModelBase, IPasswordRequester, IConfirmedPasswordRequester
    {
        private IUserManager _userManager;
        private RelayCommand<KeyEventArgs> _register;

        public bool IsBusy
        {
            get { return CurrentOperation != null && !CurrentOperation.IsComplete; }
        }

        private OperationBase _currentOperation;
        public OperationBase CurrentOperation
        {
            get
            {
                return _currentOperation;
            }
            private set
            {
                _currentOperation = value;
                RaisePropertyChanged("CurrentOperation");
                RaisePropertyChanged("IsBusy");
            }
        }


        RegistrationData _regData;
        public RegistrationData RegData
        {
            get
            {

                return _regData;

            }
        }


        /// <summary>
        /// Gets or sets a function that returns the password.
        /// </summary>
        public Func<string> PasswordAccessor
        {
            get
            {
                return _regData.PasswordAccessor;
            }
            set
            {
                _regData.PasswordAccessor = value;
            }
        }


        /// <summary>
        /// Gets or sets a function that returns the password confirmation.
        /// </summary>
        public Func<string> PasswordConfirmationAccessor
        {
            get
            {
                return _regData.PasswordConfirmationAccessor;
            }
            set
            {
                _regData.PasswordConfirmationAccessor = value;
            }
        }


        /// <summary>
        /// Command to execute login process
        /// </summary>
        public RelayCommand<KeyEventArgs> Register
        {
            get
            {
                return _register;
            }
        }




        INavigationService _navigationService;

        /// <summary>
        /// ctor with parameter for user manager instance
        /// </summary>
        /// <param name="usermanager">A instance of an implementation of IUserManager</param>

        public RegistrationViewModel(IUserManager usermanager, INavigationService navigationService)
        {


            _navigationService = navigationService;
            _userManager = usermanager;
            _regData = new RegistrationData();
            _register = new RelayCommand<KeyEventArgs>(
              (args) =>
              {
                  if (args == null || args.Key == Key.Enter)
                      ExecRegisterCommand();
              },
              (args) => { return ValidateRegisterCommand(); }
              );

            //cut and paste this line to your ctor
            _cancel = new RelayCommand(ExecCancel, CanCancel);

        }


        private bool ValidateRegisterCommand()
        {
            return !IsBusy;
        }

        //executes the registration process
        private void ExecRegisterCommand()
        {
            if (!_regData.HasValidationErrors)
            {
                _regData.Question = "12345678";
                _regData.Answer = "12345678";
                _regData.FriendlyName = "blablabla";
                _register.RaiseCanExecuteChanged();

                _userManager.RegisterAsync(_regData, _regData.Password, (operation) =>
                {

                    _register.RaiseCanExecuteChanged();
                    if (!operation.IsCanceled)
                    {
                        if (operation.HasError)
                        {
                            MessageBox.Show(operation.Error.Message);
                            GalaSoft.MvvmLight.Messaging.Messenger.Default.Send<Exception>(operation.Error);
                            operation.MarkErrorAsHandled();
                        }
                        else if (operation.Value == CreateUserStatus.Success)
                        {

                            //if registration was successful then login
                            _userManager.LoginAsync(_regData.ToLoginParameters(), (e) =>
                            {
                                //MessageBox.Show("4");
                                if (!operation.IsCanceled)
                                {
                                    if (operation.HasError)
                                    {
                                        Messenger.Default.Send<Exception>(operation.Error);
                                        operation.MarkErrorAsHandled();

                                    }
                                    else if (e.LoginSuccess)
                                    {
                                        _navigationService.CloseRegistration();
                                        _navigationService.CloseLogin();
                                        _navigationService.Navigate(NavigationTargets.Projects);

                                    }
                                    else
                                    {

                                    }
                                }
                            });
                        }
                        else if (operation.Value == CreateUserStatus.DuplicateUserName)
                        {

                            _regData.ValidationErrors.Add(new ValidationResult(ErrorResources.CreateUserStatusDuplicateUserName, new string[] { "UserName" }));
                        }
                        else if (operation.Value == CreateUserStatus.DuplicateEmail)
                        {
                            _regData.ValidationErrors.Add(new ValidationResult(ErrorResources.CreateUserStatusDuplicateEmail, new string[] { "Email" }));
                        }
                        else
                        {
                            Messenger.Default.Send<ErrorMessage>(new ErrorMessage("#GENERIC_ERROR" + ErrorResources.ErrorWindowGenericError));
                        }
                    }

                });
            }
        }


        private RelayCommand _cancel;
        public RelayCommand Cancel
        {
            get
            {
                return _cancel;
            }
        }

        /// <summary>
        /// Checks whether the Cancel command is executable
        /// </summary>
        private bool CanCancel()
        {
            return true;
        }

        /// <summary>
        /// Executes the Cancel command 
        /// </summary>
        private void ExecCancel()
        {
            _navigationService.CloseRegistration();
        }




    }
}
